package com.fit.toysShop.pages;

import org.apache.tapestry5.annotations.ApplicationState;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;

import com.fit.toysShop.asobject.PurchaseItemBasketAS;
import com.fit.toysShop.beans.PurchaseItemBean;
import com.fit.toysShop.interfaces.Product;
import com.fit.toysShop.interfaces.PurchaseItem;
import com.fit.toysShop.service.Products;


public class BasketEntry {
	@Property
	@Persist
	private int quantity;

	@Inject
	private Products products;

	// ASO 
	@ApplicationState
	private PurchaseItemBasketAS purchaseItemBasketAS;

	@Persist
	private Product chosenProduct;

	public void setChosenProduct(Product chosenProduct) {
		this.chosenProduct = chosenProduct;
	}
	public Product getChosenProduct() {
		return chosenProduct;
	}

	Object onActivate(String productName)
	{
		chosenProduct = products.retrieveSingleProduct(productName);
		if (chosenProduct == null) return EntryPurchase.class;
		return null;
	}
	
	@OnEvent (value="submit", component="basketEntryForm")
	Object onFromSubmit() {
		PurchaseItem prod = new PurchaseItemBean();
		prod.setId(chosenProduct.getName());
		prod.setQuantity(this.quantity);
		prod.setTotalPrice(this.quantity * chosenProduct.getPrice());
		prod.setCanceled(false);
		prod.setProduct(chosenProduct);

		purchaseItemBasketAS.getPurchaseItemBasket().put(prod.getId(), prod);
		return EntryPurchase.class;		
	}	
}
